package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.entity.Setmeal;
import com.itheima.service.CatergoryService;
import com.itheima.service.DishFlaverService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @email 1572178030@qq.com
 * @author:黄海宾
 * @date: 2023/2/9  15:15
 */

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CatergoryService catergoryService;

    @Autowired
    private DishFlaverService dishFlaverService;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {

        dishService.dishWithFlaver(dishDto);
        return R.success("添加成功");
    }

    //关联的是种类层和菜单层
    @GetMapping("/page")
    public R<Page> queryPage(int page, int pageSize, String name) {
        Page pageBean = new Page(page, pageSize);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        //封装排序
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageBean, queryWrapper);

        //得到pageBean中的值拷贝到新的page中
        Page page1 = new Page();
        BeanUtils.copyProperties(pageBean, page1, "records");

        List<Dish> records = pageBean.getRecords();

        List<DishDto> list = records.stream().map(item -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();

            Category byId = catergoryService.getById(categoryId);
            dishDto.setCategoryName(byId.getName());

            return dishDto;
        }).collect(Collectors.toList());

        page1.setRecords(list);
        return R.success(page1);
    }

    /*
     * 编辑用户*/
    @GetMapping("/{id}")
    public R<DishDto> editDish(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return R.success(dishDto);
    }

    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("id的值{}", ids);
        List<Dish> dishes = dishService.listByIds(ids);
        dishService.removeByIds(ids);

        dishes.stream().map(item -> {
            dishFlaverService.removeById(item.getId());
            return true;
        });

        return R.success("删除成功");
    }

    /*
     * 修改状态*/
    @PostMapping("/status/{type}")
    public R<String> statusEdit(@PathVariable int type, @RequestParam List<Long> ids) {
        List<Dish> dishes = dishService.listByIds(ids);
        for (Dish dish : dishes) {
            if (!(dish.getStatus() == type)) {
                dish.setStatus(type);
                dishService.updateById(dish);
                return R.success("修改成功");
            }
        }
        return R.error("修改失败");

    }

    /*
    套餐管理
    新增套餐中的添加菜品
    * */
/*    @GetMapping("/list")
    public R<List<Dish>> getByIdList(Long categoryId) {
        //接收前端的category的id
        //Long categoryId = category.getId();

        //找到category的id, 找到对应表Dish中的categoryId
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId, categoryId); //select * from dish where categoryId = #{categoryId}

        List<Dish> list = dishService.list(queryWrapper);
        log.info("list{}==23==23=", list);
        return R.success(list);

    }*/

    /*
        @GetMapping("/list")
        public R<List<DishDto>> getByIdList(Long categoryId, int status) {
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dish::getCategoryId, categoryId);
            List<Dish> dishList = dishService.list(queryWrapper);

            List<DishDto> dishDtosList = dishList.stream().map(item -> {
                DishDto dishDto = new DishDto();
                LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(DishFlavor::getDishId, item.getId());
                List<DishFlavor> dishFlavorsList = dishFlaverService.list(queryWrapper1);
                dishDto.setFlavors(dishFlavorsList);
                return dishDto;
            }).collect(Collectors.toList());

            return R.success(dishDtosList);
        }
    */

    /*
    * A. 根据分类ID查询，查询目前正在启售的菜品列表 (已实现)

      B. 遍历菜品列表，并查询菜品的分类信息及菜品的口味列表

      C. 组装数据DishDto，并返回（
      * 1，找到菜品的数据保存到DishDto中，
      * 2. 找到对应的分类的名字保存到DisDto中,
      * 3. 找到分类口味中的id到DishDto中）
    * */


    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //构造查询条件(根据分类id查询，找到正在起售的找出来)
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = list.stream().map(item -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //查询到分类id,设置菜品的分类名子
            Long categoryId = item.getCategoryId();//分类id
            Category category = catergoryService.getById(categoryId);

            if (category != null) {
                String categoryNmae = category.getName();
                dishDto.setCategoryName(categoryNmae);
            }
            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> DisQueryWrapper = new LambdaQueryWrapper<>();
            DisQueryWrapper.eq(DishFlavor::getDishId, dishId);

            List<DishFlavor> dishFlavorList = dishFlaverService.list(DisQueryWrapper);

            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        return R.success(dishDtoList);
    }

}
